import React from 'react';
import { PostForm } from 'services';
const MAX_WIDTH = 800; // 图片最大宽度
export default () => {
    const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files === null) return
        if (event.target.files.length === 0) return
        const file = event.target.files[0]
        const reader = new FileReader()
        reader.onload = async function() {
            const dataUrl = await compress(reader.result as string, 90, 'image/jpeg')
            const blob = dataUrlToBlob(dataUrl as string, 'image/jpeg')
            upload(blob, file.name)
        }
        reader.readAsDataURL(file)
    }
    const compress = (base64: string, quality: number, mimeType: string) => {
        const canvas = document.createElement('canvas')
        const img = document.createElement('img')
        img.crossOrigin = 'anonymous'
        return new Promise((resolve, reject) => {
            img.src = base64
            img.onload = function() {
                let targetWidth: number, targetHeight: number
                if (img.width > MAX_WIDTH) {
                    targetWidth = MAX_WIDTH
                    targetHeight = (img.height * MAX_WIDTH) / targetWidth
                } else {
                    targetHeight = img.height
                    targetWidth = img.width
                }
                canvas.width = targetWidth
                canvas.height = targetHeight
                const context = canvas.getContext('2d')
                context?.clearRect(0, 0, targetWidth, targetHeight)
                context?.drawImage(img, 0, 0, targetWidth, targetHeight)
                // const imageData = canvas.toDataURL(mimeType, quality / 100)
                // resolve(imageData)
                /** Blob可以减少传输量 */
                canvas.toBlob((blob) => {
                    resolve(blob)
                }, mimeType, quality / 100)
            }
        })
    }
    const dataUrlToBlob = (base64: string, mimeType: string) => {
        const bytes = window.atob(base64.split(',')[1])
        const buffer = new ArrayBuffer(bytes.length)
        const ia = new Int8Array(buffer)
        for (let i = 0; i < bytes.length; i ++) {
            ia[i] = bytes.charCodeAt(i)
        }
        return new Blob([ia], { type: mimeType })
    }
    const upload = (blob: Blob, name: string) => {
        const data = {
            file: blob,
            name
        }
        PostForm('/upload/image', data)
    }

    return (
        <div>
            <input type="file" onChange={onFileChange}/>
        </div>
    )
}